package com.entrogy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.ClassScoreOverviewEntity;
import com.entrogy.bean.Msg;
import com.entrogy.bean.StudentCourseScoreEntity;
import com.entrogy.bean.StudentScoreEntity;
import com.entrogy.bean.*;
import com.entrogy.service.ClassService;
import com.entrogy.service.ExamService;
import com.entrogy.service.StudentScoreService;
import com.entrogy.service.StudentService;
import com.entrogy.utils.EasyExcelUtil;
import com.entrogy.utils.constants.ErrorEnum;
import io.netty.util.internal.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


//多校版成绩模块的成绩表分开存放，所有学校每个月产生一张表（由定时任务产生）表名为"eaxm_score"+本月日期（如201906）的格式
@RestController
@RequestMapping(value = "/studentScore")
@Api(description = "学生成绩管理操作的相关接口")
/**
 * @ClassName StudentScoreController
 * @Description
 * @Author luoxingjiang
 * @Date 2019/6/4 0004 下午 4:29
 * @Version 1.0
 **/
public class StudentScoreController {

    private Logger logger = LoggerFactory.getLogger(StudentScoreController.class);

    @Autowired
    private StudentScoreService studentScoreService;

    @Autowired
    private ExamService examService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private EasyExcelUtil easyExcelUtil;

    @Autowired
    private ClassService classService;


    /**
     * @param examId
     * @param classType
     * @param classId
     * @return 学生所有科目成绩列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "classType", value = "班级类型", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "classId", value = "班级id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "studentId", value = "学生id", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "学生所有科目成绩列表")
//    @RequiresPermissions("score:list")
    public Msg getStudentScoreList(Integer examId, Integer classType, Integer classId, Integer studentId) {
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        String scoreTableName = examService.findScoreTableNameByExamId(examId);
        List<StudentScoreEntity> studentScoreList = studentScoreService.findStudentScoreList(examId, classType, classId, scoreTableName, schoolCode, false, studentId);
        // 查询该次考试的排名生成情况用于前端动态显示排名情况
        List<String> columnList = listColumn(examId);
        return Msg.success().add("studentScoreList", studentScoreList).add("columnList", columnList);
    }

    private List<String> listColumn(Integer examId) {
        JSONObject rankGenerateRecordList = examService.getRankGenerateRecord(examId);
        List<String> columnList = new ArrayList<>();
        if (rankGenerateRecordList != null) {
            for (String column : rankGenerateRecordList.keySet()) {
                // 当该排名信息生成记录为1时，前端才显示
                if (rankGenerateRecordList.getInteger(column).equals(1))
                    columnList.add(column);
            }
        }
        return columnList;
    }


    /**
     * @param examId
     * @param classId
     * @return 学生单科目成绩列表
     */
    //查询某班单科成绩列表，根据当前用户的teacherId来显示当前用户能够录入的成绩
    @ApiOperation(value = "查询某班单科成绩列表，根据当前用户的teacherId来显示当前用户能够录入的成绩")
    @RequestMapping(value = "/courseList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "classId", value = "班级id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "courseId", value = "科目Id", dataType = "Integer", paramType = "query"),
    })
//    @RequiresPermissions("score:list")
    public Msg getStudentCourseScore(Integer examId, Integer classId, Integer courseId) {
        String scoreTableName = examService.findScoreTableNameByExamId(examId);
        String teacherId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        Map<String, Object> param = new HashMap<>();
        param.put("examId", examId);
        param.put("classId", classId);
        param.put("schoolCode", schoolCode);
        param.put("teacherId", teacherId);
        param.put("scoreTableName", scoreTableName);
        param.put("courseId", courseId);
        List<StudentCourseScoreEntity> studentCourseScoreList = studentScoreService.findStudentCourseScoreList(param);
        return Msg.success().add("studentCourseScoreList", studentCourseScoreList);
    }

    /**
     * @param studentCourseScoreEntities
     * @return 成绩更新，因为在创建考试时每个学生该次考试的所有考试科目已经创建，成绩默认为0，所以成绩只有更新没有插入
     */
    @RequestMapping(value = "/updateScore", method = RequestMethod.PUT)
    @ApiOperation(value = "成绩插入/更新")
//    @RequiresPermissions("score:add")
    public Msg updateScore(@RequestBody List<StudentCourseScoreEntity> studentCourseScoreEntities) {
        logger.debug("教师正在进行学生成绩录入=》" + studentCourseScoreEntities);
        if (studentCourseScoreEntities.size() == 0) {
            return Msg.fail(ErrorEnum.E_101, "您还没有录入任何成绩！");
        }
        boolean result = studentScoreService.updateScore(studentCourseScoreEntities);
        if (result) {
            return Msg.success();
        }
        return Msg.fail(ErrorEnum.E_101, ErrorEnum.E_101.getErrorMsg());
    }


    /**
     * 根据考试id查看班级成绩概览
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/classScoreOverview", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "参数字符串", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "根据考试id查看班级成绩概览")
//    @RequiresPermissions("score:list")
    public Msg getClassScoreOverview(String params) {
        JSONObject jsonObject = JSONObject.parseObject(params);
        //从参数中查询出考试的所有班级
        JSONArray examClassIdList = jsonObject.getJSONArray("examClassIds");
        List<Integer> classIds = JSONObject.parseArray(examClassIdList.toJSONString(), Integer.class);
        //从参数中查询出考试的所有班级
        Integer examId = jsonObject.getInteger("examId");
        List<GradeScoreOverviewEntity> overviewList = getGradeScoreOverviewList(examId, classIds, null);
        return Msg.success().add("overviewList", overviewList);
    }

    @GetMapping("/downloadScoreModel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "examName", value = "考试名称", dataType = "String", paramType = "query")
    })
    @ApiOperation(value = "导出成绩模板")
    public void cooperation(HttpServletRequest request, HttpServletResponse response) {
        Integer examId = Integer.valueOf(request.getParameter("examId"));
        String examName = request.getParameter("examName");
        ServletOutputStream out;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(examName + "成绩表", "utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
            String scoreTableName = examService.findScoreTableNameByExamId(examId);
            //List<JSONObject> scoreList = studentScoreService.findStudentScoreListForExport(examId, staticCourses, scoreTableName);
            //查询出所有班级此次考试的成绩用于excel的导出
            List<StudentScoreEntity> scoreList = studentScoreService.findStudentScoreList(examId, null, null, scoreTableName, schoolCode, true, null);
            logger.debug("scoreList=>" + scoreList.toString());
            //写sheet1，表头数据动态传入
            //查询该场考试考了哪些科目以及科目的分数，用于设置动态表头并实现分数的填充
            List<StaticCourseEntity> staticCourses = studentScoreService.findExamStaticCourse(examId);
            List<List<String>> head = new ArrayList<>();
            List<String> headCoulumn1 = new ArrayList<>();
            List<String> headCoulumn2 = new ArrayList<>();
            List<String> headCoulumn3 = new ArrayList<>();
            headCoulumn1.add("考试编号");
            headCoulumn1.add("学号");
            headCoulumn2.add("" + examId);
            headCoulumn2.add("班级");
            headCoulumn3.add("科目编号");
            headCoulumn3.add("姓名");
            head.add(headCoulumn1);
            head.add(headCoulumn2);
            head.add(headCoulumn3);
            for (int i = 0; i < staticCourses.size(); i++) {
                List<String> headCoulumn = new ArrayList<>();
                headCoulumn.add(staticCourses.get(i).getId() + "");
                headCoulumn.add(staticCourses.get(i).getCourseName());
                head.add(headCoulumn);
            }
            // 动态添加表头，适用一些表头动态变化的场景
            EasyExcel.write(out)
                    // 这里放入动态头
                    .head(head).sheet("sheet1")
                    // 当然这里数据也可以用 List<List<String>> 去传入
                    .doWrite(createDynamicModelList(scoreList, staticCourses));
            // 关闭流
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/importScore")
    @ApiOperation(value = "导入成绩")
    public Msg importScore(@RequestParam("excelFile") MultipartFile excelFile, @RequestParam("examId") Integer examId) throws IOException {
        // 判断教师要导入的成绩是不是他创建的
//        String userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
//        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
//        List<ExamEntity> examEntity = examService.findExamList(userId, schoolCode, examId);
//        if (examEntity.size() == 0) {
//            return Msg.fail(ErrorEnum.E_101, "对不起，您只能导入您自己创建的考试的成绩！");
//        }
        // 解析出来的examId，判断要导入的考试和实际传入的excel的考试id是否相同
        Integer importExamId;
        try {
            importExamId = easyExcelUtil.resolveExcelWithStudent(excelFile.getInputStream(), studentScoreService, examService, examId);
        } catch (Exception e) {
            return Msg.fail(ErrorEnum.E_90009, e.getMessage());
        }
        return Msg.success();
    }


    /**
     * 根据考试id发送该次考试的成绩信息到学生家长的小程序、短信端
     *
     * @param examId
     * @param type
     * @return
     */
    @RequestMapping(value = "/sendWeApp", method = RequestMethod.POST)
    @ApiOperation(value = "根据考试id发送该次考试的成绩信息到学生家长的小程序端")
    public Msg sendStudentScoreToWeApp(Integer examId, Integer type, Integer sendMethod, Integer[] sendClassIdList) {
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        if (Arrays.asList(sendClassIdList).contains(1)) {
            List<Integer> classIdList = examService.listExamClassId(examId);
            sendClassIdList = classIdList.toArray(new Integer[classIdList.size()]);
        }
        String scoreTableName = examService.findScoreTableNameByExamId(examId);
        // 版本更新，不用选择发送方式，只发送提示家长信息
//        if (type == null){
//            return Msg.fail(ErrorEnum.E_101, "发送失败，请选择发送方式！");
//        }
        Map<String, Object> result = studentScoreService.sendWeApp(type, sendMethod, examId, scoreTableName, schoolCode, sendClassIdList);
        List<JSONObject> sendFailList = (List<JSONObject>) result.get("sendFailList");
        List<JSONObject> sendSuccessList = (List<JSONObject>) result.get("sendSuccessList");
        return Msg.success().add("sendFailList", sendFailList).add("sendSuccessList", sendSuccessList);
    }

    @PostMapping(value = "/generateRank")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "requireCourseClassRank", value = "是否生成单科班级排名，0不需要，1需要，下同", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireCourseGradeRank", value = "是否生成单科年级排名", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireTotalScoreClassRank", value = "是否生成班级总分排名", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireTotalScoreGradeRank", value = "是否生成年级总分排名", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireScienceOrArtsClassRank", value = "是否生成理综/文综班级排名", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireScienceOrArtsGradeRank", value = "是否生成理综/文综年级排名", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireClassAvgScore", value = "是否班级平均分（包括单科和总分的平均分）", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireGradeAvgScore", value = "是否年级级平均分（包括单科和总分的平均分）", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "requireTotalScore", value = "是否生成总分(默认选中)", dataType = "Integer", paramType = "query", required = true),
    })
    @ApiOperation(value = "生成排名，包括学生单科班级排名、学生总分班级排名、总分年级排名")
    public Msg generateRank(Integer examId, Integer requireCourseClassRank, Integer requireCourseGradeRank,
                            Integer requireTotalScoreClassRank, Integer requireTotalScoreGradeRank,
                            Integer requireScienceOrArtsClassRank, Integer requireScienceOrArtsGradeRank,
                            Integer requireClassAvgScore, Integer requireGradeAvgScore, Integer requireTotalScore) {
        requireClassAvgScore = requireClassAvgScore == null ? 0 : requireClassAvgScore;
        requireGradeAvgScore = requireGradeAvgScore == null ? 0 : requireGradeAvgScore;
        String userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        logger.info("正在进行考试id为：{}的排名生成，生成方式为：requireCourseClassRank：{}，" +
                        "requireCourseGradeRank：{}，requireTotalScoreClassRank：{}，" +
                        "requireScienceOrArtsClassRank：{}，requireScienceOrArtsGradeRank：{}，requireClassAvgScore：{}，requireGradeAvgScore：{}，操作人为：{}",
                examId, requireCourseClassRank, requireCourseGradeRank, requireTotalScoreClassRank, requireScienceOrArtsClassRank, requireScienceOrArtsGradeRank, requireClassAvgScore, requireGradeAvgScore, userId);
        // 首先不管三七二十一先删除该次考试的排名生成记录，并且需要将这此考试的所有学生的所有排名信息置位null，此处涉及两张表，一张成绩表exam_scoreyyyyMM和exam_rank
        String scoreTableName = examService.findScoreTableNameByExamId(examId);
        boolean initExamRankResult = examService.initExamRank(examId, scoreTableName);

        int deleteRankGenerateRecordResult = examService.deleteRankGenerateRecord(examId);
        logger.info("删除该次的考试排名记录条数：{}", deleteRankGenerateRecordResult);
        boolean insertRankGenerateRecordResult = examService.insertRankGenerateRecord(examId, requireCourseClassRank,
                requireCourseGradeRank, requireTotalScoreClassRank,
                requireTotalScoreGradeRank, requireScienceOrArtsClassRank,
                requireScienceOrArtsGradeRank, requireClassAvgScore,
                requireGradeAvgScore);
        logger.info("插入该次考试的排名记录结果：{}", insertRankGenerateRecordResult);
        // 首先生成学生单科班级/年级排名
        if (requireCourseClassRank == 1 || requireCourseGradeRank == 1) {
            boolean generateStuCourseClassRankResult = studentScoreService.generateStuCourseClassRank(examId, scoreTableName, requireCourseClassRank, requireCourseGradeRank);
        }
        // 然后生成学生总分班级排名
        boolean generateStuTotalScoreClassRankResult = studentScoreService.generateStuTotalScoreClassRank(examId, scoreTableName, requireTotalScoreClassRank);
        // 总分年级排名
        if (requireTotalScoreGradeRank != 0) {
            boolean generateStuTotalScoreGradeRankResult = studentScoreService.generateStuTotalScoreGradeRank(examId, scoreTableName);
        }
        // 生成单科班级中位分
        boolean generateCourseClassMiddleScoreResult = studentScoreService.generateCourseClassMiddleScore(examId, scoreTableName);
        // 生成单科年级中位分
        boolean generateCourseGradeMiddleScoreResult = studentScoreService.generateCourseGradeMiddleScore(examId, scoreTableName);
        // 计算理综/文综分数
        boolean generateScienceOrArtsResult = studentScoreService.generateScienceOrArts(examId, scoreTableName);
        if (!generateScienceOrArtsResult) {
            logger.info("此次考试=>" + examId + "没有考理综/文综成绩，不会生成理综/文综总分！");
            if (requireScienceOrArtsClassRank == 1 || requireScienceOrArtsGradeRank == 1) {
                return Msg.fail(ErrorEnum.E_101, "排名生成成功，生成理综/文综排名失败，该次考试未考理科综合或者文科综合！");
            }
        } else {
            // 生成理综/文综班级、年级排名
            if (requireScienceOrArtsClassRank == 1 || requireScienceOrArtsGradeRank == 1) {
                boolean generateScienceOrArtsRankResult = studentScoreService.generateScienceOrArtsRank(examId, scoreTableName, requireScienceOrArtsClassRank, requireScienceOrArtsGradeRank);
            }
        }
        return Msg.success();
    }

    /**
     * 小程序成绩分析接口，根据uid不同返回不同的数据
     *
     * @param examId
     * @return
     */
    @RequestMapping(value = "/findScoreDetail", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "uId", value = "用户id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "selectClassId", value = "教师查看时选择查看哪个班级的成绩", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "小程序成绩分析接口，根据uid不同返回不同的数据")
    public Msg findScoreDetail(Integer examId, String uId, Integer selectClassId) {
        // 查询出该次考试要显示那些排名信息
        List<String> columnList = listColumn(examId);
        // 如果用户id以3开头，那么为家长，查询子女的成绩详情
        if (uId.startsWith("3")) {
            // 根据家长id查询出学生的id
            List<Integer> stuIds = studentService.findStuIdsByParentId(uId);
            // 根据考试id和stuId查询学生成绩信息
            List<StudentScoreEntity> studentScoreList = new ArrayList<>();
            for (int i = 0; i < stuIds.size(); i++) {
                String scoreTableName = examService.findScoreTableNameByExamId(examId);
                // 当学生id确定时，tempList只有一个学生的成绩信息
                List<StudentScoreEntity> tempList = studentScoreService.
                        findStudentScoreList(examId, null, null, scoreTableName, null, false, stuIds.get(i));
                if (tempList.size() == 0) {
                    continue;
                }
                StudentScoreEntity studentScoreEntity = tempList.get(0);
                // 根据学生id找到他的所属班级
                Integer classId = studentService.findClassIdByStuId(stuIds.get(i));
                // 将学生所考科目的单科平均分录入
                StudentEntity studentEntity = studentService.getStudentById(stuIds.get(i));
                List<ClassScoreOverviewEntity> classScoreOverviewList = studentScoreService.findClassScoreOverviewList(examId, classId, studentEntity.getGradeId(), scoreTableName);
                for (int j = 0; j < studentScoreEntity.getScoreDetailEntities().size(); j++) {
                    ScoreDetailEntity temp = studentScoreEntity.getScoreDetailEntities().get(j);
                    for (int h = 0; h < classScoreOverviewList.size(); h++) {
                        ClassScoreOverviewEntity classScore = classScoreOverviewList.get(h);
                        if (classScore.getCourseId().equals(temp.getCourseId())) {
                            temp.setCourseScoreAvg(classScore.getClassAvgScore()).setCourseGradeScoreAvg(classScore.getGradeAvgScore());
                        }
                    }
                }
                studentScoreList.addAll(tempList);
            }
            return Msg.success().add("studentScoreList", studentScoreList).add("type", 3).add("columnList", columnList);
        } else if (uId.startsWith("1")) {
            // 如果用户id以1开头，那么为教师，查询该教师所教班级的成绩详情
            // 查询出该次考试的所有班级
            List<Integer> classIds = examService.listExamClassId(examId);
            List<GradeScoreOverviewEntity> gradeScoreOverviewList = getGradeScoreOverviewList(examId, classIds, selectClassId);
            return Msg.success().add("overviewList", gradeScoreOverviewList).add("type", 1).add("columnList", columnList);
        }
        return null;
    }

    /**
     * 已弃用，升级到腾讯云服务器后，mysql的版本为5.7导致rank()方法不能使用
     *
     * @param examId
     * @param classType
     * @param classId
     * @return 学生所有科目成绩列表---排名更新版本
     */
    @RequestMapping(value = "/listByRank", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "classType", value = "班级类型", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "classId", value = "班级id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "studentId", value = "学生id", dataType = "Integer", paramType = "query"),
    })
//    @RequiresPermissions("score:list")
    @ApiOperation(value = "学生所有科目成绩列表")
    public Msg getStudentScoreListByRank(Integer examId, Integer classType, Integer classId, Integer studentId) {
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        String scoreTableName = examService.findScoreTableNameByExamId(examId);
        List<StudentScoreEntity> studentScoreList = studentScoreService.findStudentScoreListByRank(examId, classType, classId, scoreTableName, schoolCode, false, studentId);
        return Msg.success().add("studentScoreList", studentScoreList);
    }

    //根据动态列生成动态的数据，
    private List<List<Object>> createDynamicModelList(List<StudentScoreEntity> scoreList, List<StaticCourseEntity> staticCourses) {
        List<List<Object>> rows = new ArrayList<>();
        for (int i = 0; i < scoreList.size(); i++) {
            StudentScoreEntity temp = scoreList.get(i);
            List<ScoreDetailEntity> tempScoreDetailEntity = temp.getScoreDetailEntities();
            List<Object> row = new ArrayList<>();
            row.add(temp.getStudentId());
            row.add(temp.getClassName());
            row.add(temp.getStudentName());
            for (int k = 0; k < staticCourses.size(); k++) {
                StaticCourseEntity staticCourseEntity = staticCourses.get(k);
                for (int j = 0; j < tempScoreDetailEntity.size(); j++) {
                    //写每一行成绩数据时，需要比较静态课程id是否对应，否则成绩可能会错位
                    if (staticCourseEntity.getId() == tempScoreDetailEntity.get(j).getStaticCourseId().intValue()) {
                        row.add(tempScoreDetailEntity.get(j).getScore());
                    }
                }
            }
            rows.add(row);
        }
        return rows;
    }

    private List<GradeScoreOverviewEntity> getGradeScoreOverviewList(Integer examId, List<Integer> classIds, Integer selectClassId) {
        String scoreTableName = examService.findScoreTableNameByExamId(examId);
        List<GradeScoreOverviewEntity> overviewList = new ArrayList<>();
        // 根据要考试的班级的id的集合，查询出年级的集合，里面包含班级的集合
        List<GradeEntity> gradeEntities = examService.findExamGradeByClassIds(classIds, examId);
        // 查询出所有年级的所有班级的班级分数概览
        for (int i = 0; i < gradeEntities.size(); i++) {
            GradeEntity temp1 = gradeEntities.get(i);
            int gradeId = temp1.getClassId();
            for (int j = 0; j < temp1.getGradeEntities().size(); j++) {
                GradeEntity temp = temp1.getGradeEntities().get(j);
                ClassEntity classEntity = new ClassEntity();
                classEntity.setId(temp.getClassId());
                classEntity.setClassName(temp.getClassName());
                if (selectClassId != null) {
                    if (!selectClassId.equals(classEntity.getId())) {
                        continue;
                    }
                }
                List<ClassScoreOverviewEntity> classScoreOverviewList = studentScoreService.findClassScoreOverviewList(examId, temp.getClassId(), gradeId, scoreTableName);
                if (classScoreOverviewList.size() > 0) {
                    overviewList.add(new GradeScoreOverviewEntity(classEntity, classScoreOverviewList));
                }
            }
        }
        return overviewList;
    }
}
